import 'dart:async';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sports_new/controller/match/list/match_page_logic.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:sports_new/resources/styles.dart';
import 'package:sports_new/utils/routes.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/utils/widget_utils.dart';
import 'package:sports_new/widgets/loading/loading_widget.dart';
import 'package:visibility_detector/visibility_detector.dart';

import '../../widgets/base/qkd_text.dart';

class MatchPage extends StatefulWidget {
  const MatchPage({super.key});

  @override
  State<MatchPage> createState() => _MatchPageState();
}

class _MatchPageState extends State<MatchPage>
    with TickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  final logic = Get.put(MatchPageLogic(),permanent: true);
  late final TabController tabC = TabController(length: 2, vsync: this);

  bool visible = false;

  @override
  void initState() {
    super.initState();
    tabC.addListener(() {
      logic.headIndex = tabC.index;
      update();
    });
    Timer.periodic(const Duration(seconds: 10), (timer) {
      if (!visible) {return;}
      logic.getMatchController().getMatch();
    });
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return GetBuilder<MatchPageLogic>(
      builder: (MatchPageLogic logic) => Scaffold(
        backgroundColor: Colours.greyF2F3F7,
        body: VisibilityDetector(
          onVisibilityChanged: (info) {
            visible = !info.visibleBounds.isEmpty;
          },
          key: const Key("match key"),
          child: LoadingWidget<bool>(
            reconnect: logic.getRefresh,
            isLoading: logic.isLoading,
            loading: Container(),
            data: false,
            child: () => Stack(
              alignment: Alignment.topCenter,
              children: [
                Image.asset(
                  Utils.getImgPath("nav_head_back.png"),
                  width: Get.width,height: Get.width*128/375
                ),
                Column(
                  children: [
                    AppBar(
                      backgroundColor: Colours.transparent,
                      title: Styles.tabbar(
                        tabs: [
                          Image.asset(
                            logic.headIndex == 0
                              ? Utils.getImgPath("zq_choose.png")
                              : Utils.getImgPath("zq_unchoose.png"),
                            width: 68,
                            height: 44,
                          ),
                          Image.asset(
                            logic.headIndex == 1
                              ? Utils.getImgPath("lq_choose.png")
                              : Utils.getImgPath("lq_unchoose.png"),
                            width: 68,
                            height: 44
                          ),
                        ],
                        controller: tabC,
                        scrollable: true,
                        labelPadding: EdgeInsets.zero,
                        indicatorBottom: 6,
                        labelColor: Colours.white,
                        unselectedLabelColor: Colours.white,
                        onTap: (value) {
                          Utils.onEvent('match_tab', params: {'tab': value});
                        },
                      ),
                      leading: Opacity(
                        opacity: logic.opacity,
                        child: IconButton(
                          onPressed: goSetting,
                          icon: Image.asset(
                            Utils.getImgPath('match_config.png'),
                            width: 24,
                            height: 24,
                            color: Colours.text,
                          )
                        )
                      ),
                      actions: [
                        Opacity(
                          opacity: logic.opacity,
                          child: GestureDetector(
                            onTap: goFilter,
                            child: Container(
                              margin: const EdgeInsets.only(right: 16),
                              child: Image.asset(
                                Utils.getImgPath('match_filter.png'),
                                width: 22,
                                fit: BoxFit.fitWidth,
                                color: Colours.text,
                              )
                            )
                          )
                        )
                      ]
                    ),
                    Expanded(
                      child: TabBarView(
                        physics: const ClampingScrollPhysics(),
                        controller: tabC,
                        children: List.generate(2, (index) => body(index)),
                      )
                    )
                  ]
                )
              ]
            ),
          )
        )
      ),
    );
  }

  Widget body(int index) {
    return GetBuilder<MatchPageLogic>(
      builder: (logic) {
        return LoadingWidget<bool>(
          isLoading: logic.isLoading,
          loading: Container(),
          data: false,
          child: () => Column(
            children: [
              SizedBox(
                height: 40,
                child: Styles.tabbar(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  physics: const ClampingScrollPhysics(),
                  tabs: (index == 0 ? logic.zqTabs : logic.lqTabs).map((f) {
                    return f.contains("http")?CachedNetworkImage(imageUrl: f,height: 29,fit: BoxFit.fitWidth):QkdText(f);
                  }).toList(),
                  labelPadding: EdgeInsets.zero,
                  controller: index == 0 ? logic.zqC : logic.lqC,
                  onTap: (value) {
                    Utils.onEvent(
                      'match_channel',
                      params: {'channel': index == 0 ?logic.zqTabs[index]:logic.lqTabs[index]}
                    );
                    logic.changeTab(value);
                  },
                  fontSize: 16
                ),
              ),
              Expanded(
                child: MediaQuery.removePadding(
                  context: context,
                  removeTop: true,
                  child: Container(
                    color: Colours.greyF2F3F7,
                    child: TabBarView(
                      controller: index == 0 ? logic.zqC : logic.lqC,
                      children: index == 0
                      ? List.generate(
                        logic.zqTabs.length, (index) => logic.zqPages[index]
                      )
                      : List.generate(
                        logic.lqTabs.length, (index) =>
                        logic.lqPages[index]
                        ),
                      ),
                  ),
                  ),
                ),
            ],
          ),
        );
      }
    );
  }

  goSetting() {
    Utils.onEvent('match_setting');
    if (logic.headIndex == 0) {
      Get.toNamed(Routes.zqConfig);
    } else {
      Get.toNamed(Routes.lqConfig);
    }
  }

  goFilter() {
    Utils.onEvent('match_filter');
    if (logic.headIndex == 0) {
      Get.toNamed(Routes.zqFilter, arguments: logic.zqTags[logic.soccerIndex]);
    } else {
      Get.toNamed(Routes.basketballFilter, arguments: logic.lqTags[logic.basketIndex]);
    }
  }

  @override
  bool get wantKeepAlive => true;
}
